/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tiberio.movil.servicio;

import android.util.Log;
import com.tiberio.movil.entity.*;
import com.tiberio.movil.utility.gson.GsonUtility;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;


/**
 *
 * @author Chema
 */
public class ServicioHttp extends Servicio{

    //Implementamos un patron Singleton.
    
    private static ServicioHttp servicio;
    
    
    private ServicioHttp() {
        httpclient = new DefaultHttpClient();
    }

    
    public static ServicioHttp getInstance()
    {
        if(servicio == null)
            return servicio = new ServicioHttp();
        else
            return servicio;
    }
    
    
    public ServerInfoEntity conectar(int i) {
        
        //TODO: MEJORAR CONSIDERABLEMENTE.
        try {

           
            ArrayList<String> args = new ArrayList<String>();

            args.add("id");
            args.add("");
            
            //TODO: hacer bien
            if(i==1)
            {
                args.add("j_username");
            args.add("050686c@gmail.com");
            }else
            {
            
            args.add("j_username");
            args.add("josemariapfm@hotmail.com");
            
            }
            args.add("j_password");
            args.add("05junio06");
            
            args.add("spring-security-redirect");
            args.add("");
            args.add("timezone");
            args.add("0");

            if (realizarSolicitudPost(LOGIN_URL, args, true)) {
                if (realizarSolicitudGet(URL_HOME, false)) {
                    if (obtenerSession(URL_GET_SESSION, true)) {
                        args = new ArrayList<String>();
                        args.add("session");
                        args.add(idSesion);
                        args.add("refId");
                        args.add(String.valueOf(new Date().getTime()));
                        args.add("version");
                        args.add("-1");
                        obtenerSessionPpal(AJAX_ENDPOINT + "openSession", args, true);
           
                        args.clear();
                        args.add("session");
                        args.add(idSesionPpal);
                        String RespuestajSon = realizarSolicitudPostJSON(AJAX_ENDPOINT + "GetServerInfo", args, true);
                        Log.d("MyActivity", RespuestajSon);
                        ServerInfoEntity serverInfo = null;
                        
                        
                        try{ serverInfo = gson.fromJson(RespuestajSon, ServerInfoEntity.class); }catch(Throwable t){ Log.e("MyActivity","Error:", t);}
                        
                        if (serverInfo != null) {
                            return serverInfo;
                        } else {
                            Log.e("MyActivity", "ERROR al parsear ServerInfoEntity ");
                            return null;
                        }

                    } else {
                        return null;
                    }
                }


            } else {
                return null;
            }



        } catch (Exception e) {
            Log.e("MyActivity","Error:", e);
            return null;
        }

        return null;
    }

    private boolean realizarSolicitudPost(String url, ArrayList<String> args, boolean mostrarRespuesta) throws Exception {

        HttpPost httpost = new HttpPost(url);

        //mejorar para poder enviar mas de un parametro
        if (args != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            for (int i = 0; i < args.size(); i = i + 2) {
                nvps.add(new BasicNameValuePair(args.get(i), args.get(i + 1)));
            }


            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        }



        HttpResponse response = httpclient.execute(httpost);


        Log.e("MyActivity", "Solicitud para :" + url);

        /*Log.e("MyActivity", "Cabecera :" + httpost.getAllHeaders().toString());
        for (Header a : httpost.getAllHeaders()) {
            Log.e("MyActivity", a.getValue());
        }*/

        //mostrarRespuesta(response, false);
        //httpost. .releaseConnection();
        return (response.getStatusLine().getStatusCode() == 200) || (response.getStatusLine().getStatusCode() == 302);

    }

    private void mostrarRespuesta(HttpResponse response, boolean mostrarCuerpo) throws Exception {

        Log.e("MyActivity", "Respuesta del servidor: " + response.toString());
        if (mostrarCuerpo) {

            Log.e("MyActivity", "cuerpo de la respuesta: ");
            InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
            BufferedReader in = new BufferedReader(isr);
            String linea = in.readLine();
            while (linea != null) {
                Log.e("MyActivity", linea);
                linea = in.readLine();

            }
            
            isr.close();

        }
        Log.e("MyActivity", "Post cookies:");
        List<org.apache.http.cookie.Cookie> cookies = httpclient.getCookieStore().getCookies();

        if (cookies.isEmpty()) {

            Log.e("MyActivity", "No se ha recibido ninguna cookie");

        } else {

            for (Cookie cookie : cookies) {
                Log.e("MyActivity", "cookie->" + cookie);
            }
        }
    }

    private boolean obtenerSession(String url, boolean b) throws Exception {

        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);

        Log.d("MyActivity", "Solicitud para : "+ url);
        boolean encontrado = false;
        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader in = new BufferedReader(isr);
        String linea;
        while ((linea = in.readLine()) != null && !encontrado) {
            if (linea.contains("name=\"sessionId\"")) {
                encontrado = true;
                Log.d("MyActivity", linea);
                String[] lineaAux = linea.split("\"");

                idSesion = lineaAux[5];

            }
            //Log.e("MyActivity", linea);


        }

        isr.close();
        //httpget.releaseConnection();

        return (response.getStatusLine().getStatusCode() == 200) || (response.getStatusLine().getStatusCode() == 302);


    }

    private boolean obtenerSessionPpal(String url, ArrayList<String> args, boolean mostrarRespuesta) throws Exception {


        HttpPost httpost = new HttpPost(url);

        String datosjson = "{\"session\":\"" + idSesion + "\",\"reset\":true,\"refId\":" + new Date().getTime() + ",\"version\":-1}";
        Log.e("MyActivity", "Json a enviar -> " + datosjson);
        httpost.setEntity(new StringEntity(datosjson, HTTP.UTF_8));


        //httpost.setHeaders(headers)
        httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpost.addHeader("Referer", WEB_BROWSER_URL);
        httpost.addHeader("X-Qooxdoo-Response-Type", "application/json");

        // httpost.
        HttpResponse response = httpclient.execute(httpost);


        Log.d("MyActivity", "Solicitud para :" + url);

        /*Log.e("MyActivity", "Cabeceras :");
        for (Header a : httpost.getAllHeaders()) {
            Log.e("MyActivity", a.getValue());
        }*/

        //mostrarRespuesta(response, mostrarRespuesta);
        boolean encontrado = false;
        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader in = new BufferedReader(isr);
        String linea;
        while ((linea = in.readLine()) != null && !encontrado) {
            if (linea.contains("i\":")) {
                encontrado = true;
                //Log.d("MyActivity", linea);
                String[] lineaAux = linea.split("\"");

                idSesionPpal = lineaAux[3];

            }
            Log.d("MyActivity",  "OBTENEMOS ESTE IDPPAL" + linea);


        }

        //httpost.releaseConnection();
        isr.close();


        return response.getStatusLine().getStatusCode() == 200;


    }

    private boolean realizarSolicitudGet(String sol, boolean mostrarRespuesta) throws Exception {

        HttpGet httpget = new HttpGet(sol);

        HttpResponse response = httpclient.execute(httpget);


        Log.e("MyActivity", "Solicitud para :" + sol);

        /*Log.e("MyActivity", "Cabecera :" + httpget.getAllHeaders().toString());
        for (Header a : httpget.getAllHeaders()) {
            Log.e("MyActivity", a.getValue());
        }*/

        //mostrarRespuesta(response, false);
       // httpget.releaseConnection();

        return response.getStatusLine().getStatusCode() == 200;
    }

    private String realizarSolicitudPostJSON(String url, ArrayList<String> args, boolean mostrarRespuesta) throws Exception {

        
        try{
        HttpPost httpost = new HttpPost(url);




        /*
         * wc.Headers.Add("Content-Type: application/json; charset=UTF-8");
         * wc.Headers.Add(string.Format("Referer: {0}", new Uri(host,
         * "index.aspx"))); wc.Headers.Add("X-Qooxdoo-Response-Type:
         * application/json");
         */

        String datosjson = GsonUtility.toJson(args);
        
        Log.d("", "Solicitud para: "+ url);
        Log.d("", "Datos a enviar: "+ datosjson);
        
        
        httpost.setEntity(new StringEntity(datosjson, HTTP.UTF_8));


        //httpost.setHeaders(headers)
        httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpost.addHeader("Referer", WEB_BROWSER_URL);
        httpost.addHeader("X-Qooxdoo-Response-Type", "application/json");

        // httpost.
        HttpResponse response = httpclient.execute(httpost);

        //httpost.releaseConnection();

        if (response.getStatusLine().getStatusCode() != 400) {
            InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
            BufferedReader in = new BufferedReader(isr);
            
            String a = in.readLine();
            
            isr.close();
            return a;
        } else {
            return "";
        }
        }
        catch(Throwable t)
        {
            Log.e("MyActi", "ERROR en la solicitud", t);
            return "";
        }


    }

    private String realizarSolicitudPoll(String args) throws Exception {

        HttpPost httpost = new HttpPost(AJAX_ENDPOINT + "Poll");




        /*
         * wc.Headers.Add("Content-Type: application/json; charset=UTF-8");
         * wc.Headers.Add(string.Format("Referer: {0}", new Uri(host,
         * "index.aspx"))); wc.Headers.Add("X-Qooxdoo-Response-Type:
         * application/json");
         */

        String datosjson = "{\"session\":\"" + idSesionPpal + "\",\"sequenceid\":" + secuentId++ + ",\"requestid\":" + requestId++ + ",\"requests\":\""+args+"\"}";
        httpost.setEntity(new StringEntity(datosjson, HTTP.UTF_8));

        
        Log.e("MyActivity", "Enviamos ->" + datosjson);
        
        //httpost.setHeaders(headers)
         httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpost.addHeader("Referer", WEB_BROWSER_URL);
        httpost.addHeader("X-Qooxdoo-Response-Type", "application/json");
        

        // httpost.
        HttpResponse response = httpclient.execute(httpost);

       

        if (response.getStatusLine().getStatusCode() != 400)
        {
            InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
            BufferedReader in = new BufferedReader(isr);
            String r = in.readLine();
            Log.e("MyActivity", "Recibimos ->" + r);
            isr.close();
             //httpost.releaseConnection();
            return r;
        } else {
            mostrarRespuesta(response, false);
             //httpost.releaseConnection();
            return null;
        }



    }

    public PlayerInfoEntity getPlayerInfo() {
        try
        {
            ArrayList<String> args = new ArrayList<String>(); 
            args.add("session");
            args.add(idSesionPpal);
            String RespuestajSon = realizarSolicitudPostJSON(AJAX_ENDPOINT + "GetPlayerInfo", args, true);
            PlayerInfoEntity pieRespuesta = gson.fromJson(RespuestajSon, PlayerInfoEntity.class);

            if (pieRespuesta != null) 
            {
                
                baseId = pieRespuesta.getCiudades().get(0).getId();
                return pieRespuesta;
                
            } else {
                return null;
            }

        } catch (Exception e) {
            Log.e("MyActivity","Error:",  e);
            return null;
        }



    }

    
    //TODO: cambiar la gestion de los nodos, no hacer aqui, o llamar de otra forma
    public BaseEntity getInfoBase() {
        try {
           
            ArrayList<PollEntity> pollArray ;
            String respuesta = realizarSolicitudPoll("WC:A\\fTIME:"+new Date().getTime()+"\\fCHAT:\\fWORLD:\\fGIFT:\\fACS:0\\fASS:0\\fCAT:0\\f");
           CityPollEntity cpe = null;
            pollArray = GsonUtility.parsearPoll(respuesta);
            boolean foroEntityEncontrado = false;
            boolean cityEntityEncontrado = false;
            
            for (PollEntity p : pollArray)
            {
                
                
                if(p instanceof ForoPollEntity && !foroEntityEncontrado)
                {
                    if("FORUM".equals(((ForoPollEntity)p).getTexto()))
                    {
                       foroEntityEncontrado = true;
                       foros = ((ForoPollEntity)p).getForos();
                    }
                   
                }
                else
                    if(p instanceof CityPollEntity && !cityEntityEncontrado)
                    {

                        if("CITIES".equals(((CityPollEntity)p).getTexto())  )
                        {
                            cityEntityEncontrado = true;
                            baseId = ((CityPollEntity)p).getTipo().getBases().get(0).getId();
                            cpe = (CityPollEntity)p;
                        }
                    } 
                   
            }
            
            if(cpe != null)
                return cpe.getTipo().getBases().get(0);
            else return null;
           
            
            
        } catch (Exception ex) {
            Log.e("MyActivity","Error:",  ex);
        }
        return null;

    }

    public BaseEntity recogerTodosRecursos(ArrayList<EdificioEntity> edificios) 
    {
        
        
        return null;
        
       
    }

    public ArrayList<RecusoEntity> recogerRecursos(int x, int y) 
    {
        //{"session":"bf4899e0-dc27-4fdd-b2c1-212c5c216048","sequenceid":365,"cityid":1493198,"posX":4,"posY":6}
        ArrayList<String> args = new ArrayList<String>();
        args.add("session");
        args.add(idSesionPpal);
        args.add("sequenceid");
        args.add(""+secuentId++);
        args.add("cityid");
        args.add(""+baseId);
        args.add("posX");
        args.add(""+x);
        args.add("posY");
        args.add(""+y);
        
        try
        {
            String respuestajSon = realizarSolicitudPostJSON(AJAX_ENDPOINT + "CollectResource", args, true);
            Log.d("recogerRecursos", respuestajSon);
            RespuestaEntity respuesta = gson.fromJson(respuestajSon, RespuestaEntity.class);
            
            //if(respuesta.)
            return respuesta.getRecursos();
           
            
        } catch (Exception e) {
            Log.e("MyActivity","Error:",  e);
            return null;
        }
        
        
        
        
        
        
        
    }
    
    public ArrayList<ForoEntity> recuperarForos()
    {
        
        if(foros != null)
            return foros;
        else
            return new ArrayList<ForoEntity> ();
            
    }

    public ArrayList<HiloEntity> getHilos(int idForo)
    {
        return null;
        
    }

    
}
